import {
  getTopic,
  like,
  cancelLike,
  collect,
  cancelCollect,
  addReply,
  removeReply,
  getTopicEventList,
  topicLikeUserList,
  getReplyList,
  TopicCollectUserList,
  TopicRewardUserList,
  likeReply,
  cancelLikeReply,
  getReplyChildList
} from '../../../api/ChatTopicController'
import {
  delFile
} from '../../../api/OssController'
import Dialog from '@vant/weapp/dialog/dialog';
let playId = null
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    active: 'topic',
    stepsActive: 0, //当前步骤条
    topic: {}, //帖子相关信息
    reply: {
      pageNum: 2,
      pageSize: 10,
      replyTotal: 0,
      end: false
    }, //评论分页管理
    focus: false, //是否弹出键盘
    bottom: 0, // 输入框距离页面底部距离（键盘高度px）
    bottomP: 0, //针对iphone手机底部安全距离
    steps: [], //当前步骤条
    content: '', //输入框内容
    replyData: {
      parentReplyId: '0',
      replyType: '1',
      file: [],
      targetId: '',
      topicId: '',
      userId: wx.getStorageSync('userId') || '1'
    }, //回复参数
    collectUserList: [], //收藏用户列表
    topicRewardUserList: [], //打赏用户列表
    //图片评论弹窗
    imageShow: false,
    // 打赏弹窗是否显示
    showReward: false,
    // 余额不足弹窗是否显示
    showPopup: false,
    // 获取子级评论列表请求参数
    queryData: {
      pageNum: 1,
      pageSize: 9999,
    },
    list: [],
    total: 0
  },
  // 一级评论查看更多
  view(ev) {
    this.setData({
      ['topic.chatTopicReplyList[' + ev.mark.index + '].view']: true
    })
  },
  // 获取子级评论列表
  async getReplyChildList(replyId, index) {
    const replyList = this.data.topic.chatTopicReplyList
    const {
      list,
      total
    } = await getReplyChildList({
      pageSize: 10,
      pageNum: replyList[index]?.total || 1,
      replyId,
      userId: app.userId
    })
    if (total <= 10) return this.setData({
      ['topic.chatTopicReplyList[' + index + '].end']: true
    })
    list.forEach(ele => {
      ele.createTime = wx.utils.formatMsgTime(ele.createTime)
    })
    this.setData({
      ['topic.chatTopicReplyList[' + index + '].children']: [...replyList[index].children, ...list],
      ['topic.chatTopicReplyList[' + index + '].total']: replyList[index].total ? replyList[index].total + 1 : 2
    })
    if (replyList[index].children.length >= total) return this.setData({
      ['topic.chatTopicReplyList[' + index + '].end']: true
    })
  },
  // 二级查看查看更多
  seeMore(ev) {
    this.getReplyChildList(ev.mark.replyId, ev.mark.index)
  },
  //获取帖子详情
  async getTopicDetail(topicId) {
    const info = {
      topicId,
      userId: wx.getStorageSync('userId') || '1'
    }
    const res = await getTopic(info)
    res.chatTopicReplyList.forEach(item => {
      let childrenCommentTotal = 0
      item.view = false
      item.createTime = wx.utils.formatMsgTime(item.createTime)
      item.children.forEach(ele => {
        childrenCommentTotal++
        ele.createTime = wx.utils.formatMsgTime(ele.createTime)
      })
      item.childrenCommentTotal = childrenCommentTotal
    })
    res.createTime = wx.utils.formatMsgTime(res.createTime)
    res.likeCount = wx.utils.formatNumber(+res.likeCount)
    res.collectCount = wx.utils.formatNumber(+res.collectCount)
    res.rewardSCoin = wx.utils.formatNumber(+res.rewardSCoin)
    res.replyCount = wx.utils.formatNumber(+res.replyCount)
    res.contentHtml = res.contentHtml.replace(/<img[^>]*style=['"][^'"]*['"][^>]*>/gi, function (match) {
      // 设置新的style属性
      // console.log(match);
      const newStyle = "width: 90%; height: 100%;text-indent: 0;";
      const newImgTag = match.replace(/style=['"][^'"]*['"]/, `style="${newStyle}"`);
      return newImgTag;
    });
    const HtmlVideo = []
    res.contentHtml = res.contentHtml.replace(/<video.*?<\/video>/gi, function (match) {
      console.log(match);
      const src = match.match(/src="(\S*)"/)[1]
      HtmlVideo.push(src)
      return '';
    })
    // console.log(res.contentHtml);
    this.setData({
      topic: res,
      HtmlVideo: HtmlVideo
    })
  },
  //获取评论列表
  async getRList() {
    const res = await getReplyList({
      pageNum: this.data.reply.pageNum,
      pageSize: this.data.reply.pageSize,
      topicId: this.data.replyData.topicId,
      userId: wx.getStorageSync('userId')
    })
    res.list.forEach(item => {
      let childrenCommentTotal = 0
      item.view = false
      item.createTime = wx.utils.formatMsgTime(item.createTime)
      item.children.forEach(ele => {
        childrenCommentTotal++
        ele.createTime = wx.utils.formatMsgTime(ele.createTime)
      })
      item.childrenCommentTotal = childrenCommentTotal
    })
    this.setData({
      'reply.replyTotal': res.totalPage,
      'topic.chatTopicReplyList': [...res.list, ...this.data.topic.chatTopicReplyList],
      'reply.pageNum': this.data.reply.pageNum + 1
    })
    if (this.data.reply.pageNum > this.data.reply.replyTotal) {
      this.setData({
        'reply.end': true
      })
    }
  },
  //获取帖子点赞用户列表
  async getTopicLikeUserList() {
    const res = await topicLikeUserList({
      pageNum: 1,
      pageSize: 10,
      topicId: this.data.replyData.topicId,
      userId: this.data.replyData.userId || '1'
    })
    this.setData({
      'topic.topicLikeUserList': res.list
    })
  },
  //获取帖子收藏用户列表
  async getTopicCollectUserList() {
    const res = await TopicCollectUserList({
      topicId: this.data.replyData.topicId,
      userId: wx.getStorageSync('userId') || '1'
    })
    this.setData({
      collectUserList: res.list
    })
  },
  //获取帖子打赏用户列表
  async getTopicRewardUserList() {
    const res = await TopicRewardUserList({
      topicId: this.data.replyData.topicId,
      userId: wx.getStorageSync('userId') || '1'
    })
    this.setData({
      topicRewardUserList: res.list
    })
  },
  //获取帖子事件列表
  async getTEventList() {
    const res = await getTopicEventList(this.data.replyData.topicId)
    // const steps = res.chatTopicEventDetailList.map(ele => ({
    //   text: ele.createTime,
    //   desc: ele.content
    // }))
    this.setData({
      steps: res.chatTopicEventDetailList
    })
  },
  //播放视频
  play(e) {
    const id = e.mark.id
    if (!playId) {
      playId = id
    }
    if (playId && playId !== id) {
      wx.createVideoContext('video' + playId, this).pause()
      playId = id
    }
  },
  //点击回复弹出键盘
  inputShow(e) {
    this.setData({
      focus: true,
      'replyData.parentReplyId': e.mark.parentReplyId,
      'replyData.replyType': e.mark.type,
      'replyData.targetId': e.target.dataset.item.userId,
    })
  },
  //弹出键盘输入框上移
  inputFocus(e) {
    if (this.data.replyData.file.length > 0) return this.setData({
      imageShow: true
    })
    this.setData({
      bottom: e.detail.height - 1,
    })
  },
  //输入框下移
  inputBlur() {
    this.setData({
      bottom: 0,

    })
  },
  //关闭图片评论弹层
  imageShowHidden() {
    this.setData({
      imageShow: false
    })
  },
  //解决输入框警告
  inputChange() {},
  //图片预览
  viewImage(ev) {
    if (ev.mark.urls) return wx.previewImage({
      urls: ev.mark.urls,
    })
    wx.previewImage({
      urls: this.data.topic.file,
      current: this.data.topic.file[ev.mark.index]
    })
  },
  //帖子操作
  async topicStatus(ev) {
    const userId = wx.getStorageSync('userId')
    if (!userId) return wx.utils.toast('请先登录')
    const type = ev.mark.type
    const FUpperType = 'has' + type.charAt(0).toUpperCase() + type.slice(1)
    const {
      topicId,
    } = this.data.topic
    if (this.data.topic[FUpperType] === '0') {
      const res = type === 'like' ? await like({
        topicId,
        userId
      }) : await collect({
        topicId,
        userId,
        content: this.data.topic.content,
        file: this.data.topic.file,
        title: this.data.topic.title
      })
      const count = type + 'Count'
      this.setData({
        ['topic.' + FUpperType + '']: '1',
        ['topic.' + count + '']: +this.data.topic[count] * 1 === this.data.topic[count] ? +this.data.topic[count] + 1 : this.data.topic[count]
      })
    } else {
      const res = type === 'like' ? await cancelLike({
        topicId,
        userId
      }) : await cancelCollect({
        topicId,
        userId
      })

      const count = type + 'Count'
      this.setData({
        ['topic.' + FUpperType + '']: '0',
        ['topic.' + count + '']: +this.data.topic[count] * 1 === this.data.topic[count] ? +this.data.topic[count] - 1 : this.data.topic[count]
      })

    }

  },
  //回复
  async reply() {
    if (!wx.getStorageSync('userId')) return wx.utils.toast('请先登录!')
    if (!this.data.content) return wx.utils.toast('请输入评论内容')
    const {
      parentReplyId,
      replyType,
      targetId,
      topicId,
      file,
      userId
    } = this.data.replyData
    const res = await addReply({
      content: this.data.content,
      parentReplyId,
      replyType,
      targetId,
      topicId,
      file,
      userId,
    })
    res.createTime = wx.utils.formatMsgTime(res.createTime)
    if (this.data.replyData.replyType !== '1') {
      const index = this.data.topic.chatTopicReplyList.findIndex(ele => ele.replyId === res.parentReplyId)
      this.setData({
        content: '',
        'topic.replyCount': +this.data.topic.replyCount + 1,
        imageShow: false,
        'replyData.file': [],
        active: 1,
        ['topic.chatTopicReplyList[' + index + '].children']: [res, ...this.data.topic.chatTopicReplyList[index].children]
      })
    } else {
      this.setData({
        content: '',
        'topic.replyCount': +this.data.topic.replyCount + 1,
        imageShow: false,
        active: 1,
        'topic.chatTopicReplyList': [res, ...this.data.topic.chatTopicReplyList],
        'replyData.file': []
      })
    }
    // wx.pageScrollTo({
    //   scrollTop: 0
    // })
  },
  //回复选择图片
  async chooseImage() {
    if (!app.userId) return wx.utils.toast('请先登录')
    if (this.data.replyData.file.length > 0) await Dialog.confirm({
      title: '温馨提示',
      message: '是否清除之前图片并重新上传？',
    })
    wx.chooseImage({
      count: 1,
      success: (res) => {
        wx.uploadFile({
          filePath: res.tempFilePaths[0],
          name: 'file',
          url: 'https://zhenpufangwu.cn:9000/utopia/admin/oss/uploadFile',
          formData: {
            userId: app.userId
          },
          success: (res) => {
            const url = JSON.parse(res.data).data
            this.setData({
              'replyData.file': [url],
              imageShow: true
            })
          },
        })
      },
    })
  },
  //清除图片
  async delImage() {
    const res = await delFile(this.data.replyData.file[0])
    this.setData({
      'replyData.file': []
    })
  },
  //点赞评论 
  async likeR(ev) {
    if (!wx.getStorageSync('userId')) return wx.utils.toast('请先登录!')
    if (this.data.topic.chatTopicReplyList[ev.mark.index].children[ev.mark.i]) {
      const params = {
        replyId: this.data.topic.chatTopicReplyList[ev.mark.index].children[ev.mark.i].replyId,
        userId: wx.getStorageSync('userId')
      }
      if (this.data.topic.chatTopicReplyList[ev.mark.index].children[ev.mark.i].hasLike !== '1') {
        await likeReply(params)
        this.setData({
          ['topic.chatTopicReplyList[' + ev.mark.index + '].children[' + ev.mark.i + '].hasLike']: '1',
          ['topic.chatTopicReplyList[' + ev.mark.index + '].children[' + ev.mark.i + '].likeCount']: +this.data.topic.chatTopicReplyList[ev.mark.index].children[ev.mark.i].likeCount + 1
        })
      } else {
        await cancelLikeReply(params)
        this.setData({
          ['topic.chatTopicReplyList[' + ev.mark.index + '].children[' + ev.mark.i + '].hasLike']: '0',
          ['topic.chatTopicReplyList[' + ev.mark.index + '].children[' + ev.mark.i + '].likeCount']: +this.data.topic.chatTopicReplyList[ev.mark.index].children[ev.mark.i].likeCount - 1
        })
      }
    } else {
      const params = {
        replyId: this.data.topic.chatTopicReplyList[ev.mark.index].replyId,
        userId: wx.getStorageSync('userId')
      }
      if (this.data.topic.chatTopicReplyList[ev.mark.index].hasLike !== '1') {
        await likeReply(params)
        this.setData({
          ['topic.chatTopicReplyList[' + ev.mark.index + '].hasLike']: '1',
          ['topic.chatTopicReplyList[' + ev.mark.index + '].likeCount']: +this.data.topic.chatTopicReplyList[ev.mark.index].likeCount + 1
        })
      } else {
        await cancelLikeReply(params)
        this.setData({
          ['topic.chatTopicReplyList[' + ev.mark.index + '].hasLike']: '0',
          ['topic.chatTopicReplyList[' + ev.mark.index + '].likeCount']: +this.data.topic.chatTopicReplyList[ev.mark.index].likeCount - 1
        })
      }
    }
  },
  //删除评论
  async delReply(ev) {
    if (!wx.getStorageSync('userId')) return wx.utils.toast('请先登录!')
    const res = await removeReply({
      replyId: ev.mark.item,
      userId: wx.getStorageSync('userId')
    })
  },
  //打赏
  reward() {
    if (!wx.getStorageSync('userId')) return wx.utils.toast('请先登录!')
    this.setData({
      showReward: true
    })
  },
  // 余额不足弹窗显示
  onCreditLow() {
    this.setData({
      showReward: false,
      showPopup: true
    })
  },
  // 打赏完成改变
  rewardResult(e) {
    if (e.detail.flag) {
      wx.utils.toast('打赏成功,感谢您的支持!')
      this.setData({
        'topic.rewardSCoin': +this.data.topic.rewardSCoin + e.detail.price,
        'topic.hasReward': '1',

      })
    } else {
      wx.utlis.toast('打赏失败,请重新尝试！')
    }
    this.setData({
      showReward: false
    })
  },
  //去私聊页面
  toChat() {
    if (!wx.getStorageSync('userId')) return wx.utils.toast('请先登录')
    wx.navigateTo({
      url: `/pkgMessage/pages/chat/index?userId=${this.data.topic.userId}&nickName=${this.data.topic.nickName}`,
    })
  },
  //去主页
  toOtherPersonalHome(e) {
    wx.navigateTo({
      url: '/pkgUser/pages/otherPersonalHome/index?userId=' + e.mark.userId,
    })
  },
  //tab切换
  tabChange(ev) {
    if (playId) {
      wx.createVideoContext('video' + playId, this).pause()
      playId = null
    }
    this.setData({
      active: ev.detail.name
    })
    if (this.data.active === 'like') this.getTopicLikeUserList()
    if (this.data.active === 'reward') this.getTopicRewardUserList()
    if (this.data.active === 'collect') this.getTopicCollectUserList()
    if (this.data.active === 'event') this.getTEventList()
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({
    topicId,
    type
  }) {
    if (type) {
      this.setData({
        focus: true,
        active: type
      })
    }
    wx.getSystemInfo({
      success: res => {
        this.setData({
          bottomP: res.screenHeight - res.safeArea.bottom
        })
      }
    })
    this.setData({
      'replyData.topicId': topicId
    })
    if (!topicId) {

      wx.switchTab({
        url: '/pages/index/index',
      })
    }
    wx.showShareMenu({
      withShareTicket: true
    })
    this.getTopicDetail(topicId)
    this.getTEventList(topicId)
    this.getTopicCollectUserList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    try {
      wx.stopPullDownRefresh()
      this.getTopicDetail(this.data.replyData.topicId)
      this.getTopicLikeUserList()
      this.getTopicRewardUserList()
      this.getTopicCollectUserList()
      this.getTEventList()
      setTimeout(() => {
        this.setData({
          'reply.pageNum': 2,
          'reply.end': false
        })
      }, 0)
    } catch (error) {
      wx.utlis.toast('加载数据失败')
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (!this.data.reply.end && this.data.active === 'comment') {
      this.getRList()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})